package com.power.doc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.power.common.util.DateTimeUtil;
import com.power.doc.builder.ApiDocBuilder;
import com.power.doc.model.ApiConfig;
import com.power.doc.utils.PropertiesUtils;

import java.io.*;

public class ApiDocMain {


    public static void main(String[] args) throws Exception {
        String configName = "config.json";
        //InputStream resource = ApiDocMain.class.getResourceAsStream("config.json");
        String filePath = new ApiDocMain().getClass().getClassLoader().getResource(configName).getPath();
        String jsonStr = null;
        //jar文件运行
        if(filePath.contains(".jar!")){
            String confPath = ApiDocMain.getPath()+"/"+configName;
            File file = new File(confPath);
            if(!file.exists()){
                file.getParentFile().mkdirs();
                jsonStr = PropertiesUtils.readJarFile(configName);
                PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(confPath), "UTF-8"));
                out.println(jsonStr);
                out.close();//记得关闭输入流
            }else{
                filePath = confPath;
                jsonStr = PropertiesUtils.readJsonData(confPath);
            }
        }else{
            jsonStr = PropertiesUtils.readJsonData(filePath);
        }
        System.out.println("读取配置文件:"+filePath);
        if(jsonStr==null){
            return;
        }
        ApiConfig mApiConfig = JSON.toJavaObject(JSONObject.parseObject(jsonStr), ApiConfig.class);
        System.out.println("读取目录:"+JSON.toJSON(mApiConfig.getSourcePaths()).toString());
        System.out.println("输出目录:"+mApiConfig.getOutPath());
        long start = System.currentTimeMillis();
        ApiDocBuilder.builderControllersApi(mApiConfig);
        long end = System.currentTimeMillis();
        DateTimeUtil.printRunTime(end, start);
    }

    public static String getPath()
    {
        String path = new ApiDocMain().getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        if(System.getProperty("os.name").contains("dows"))
        {
            path = path.substring(1,path.length());
        }
        if(path.contains("jar"))
        {
            path = path.substring(0,path.lastIndexOf("."));
            return path.substring(0,path.lastIndexOf("/"));
        }
        return path.replace("target/classes/", "");
    }

}
